<template>
  <div class="head-container">
    <el-input v-model="inventoryClassifyName" class="mb-20px" clearable placeholder="请输入分类名称">
      <template #prefix>
        <Icon icon="ep:search" />
      </template>
    </el-input>
  </div>
  <div class="head-container">
    <el-tree
ref="treeRef" :data="inventoryClassifyList" :expand-on-click-node="false"
             :filter-node-method="filterNode" :props="defaultProps" default-expand-all
             highlight-current node-key="id" @node-click="handleNodeClick"/>
  </div>
</template>

<script lang="ts" setup>
import { ElTree } from 'element-plus'
import { defaultProps, handleTree } from '@/utils/tree'
import { InventoryClassifyApi } from '@/api/wms/inventoryclassify'

defineOptions({ name: 'SystemUserDeptTree' })

const inventoryClassifyName = ref('')
const inventoryClassifyList = ref<Tree[]>([]) // 树形结构
const treeRef = ref<InstanceType<typeof ElTree>>()

/** 获得产品分类树 */
const getTree = async () => {
  const res = await InventoryClassifyApi.getInventoryClassifySimpleList()
  res.push({ id: 0, name: '顶级存货分类' })
  inventoryClassifyList.value.push(...handleTree(res))
}

/** 基于名字过滤 */
const filterNode = (name: string, data: Tree) => {
  if (!name) return true
  return data.name.includes(name)
}

/** 处理产品分类被点击 */
const handleNodeClick = async (row: { [key: string]: any }) => {
  emits('node-click', row)
}

const emits = defineEmits(['node-click'])

/** 监听inventoryClassifyName */
watch(inventoryClassifyName, (val) => {
  treeRef.value!.filter(val)
})

/** 初始化 */
onMounted?.(async () => {
  await getTree()
})
</script>
